﻿var oauthHost = "http://lhl.Service.com";
var apiHost = "http://lhl.Resource.com";
var webHost = "http://lhl.client.com";
var authorizeUrl = oauthHost + '/Authorize';
var tokenUrl = oauthHost + '/Token';
var apiUrl = apiHost + '/api/Values';
var returnUrl ='http://lhl.client.com/Account/CallBack.html';
var bearer_expires = 365;
var clientId = '222';
//注销登录地址
var signoutUrl = "/Account/LogOut";
//检测登录状态地址
var isOnLineUrl = "/api/UserInfo/IsOnLine";
//获取用户昵称
var getNickNameUrl = "/api/UserInfo/GetNickName";

// 初始化授权信息
$(function () {
    initOAuth();
});


//跳转到指定的Url
function goToUrl(url) {
    window.location.href = url;
}

//处理ReturnURL
function processReturnUrl(url) {
    var returnUrl = "";
    if (typeof (url) != 'undefined' && url.length > 0) {
        returnUrl = "?ReturnUrl=" + url;
    }
    return returnUrl;
}

// 登录跳转
function goToSignIn() {
    var nonce = 'my-nonce';

    var uri = addQueryString(authorizeUrl, {
        'client_id': clientId,
        'redirect_uri': returnUrl + '?returnUrl=' + encodeURIComponent(window.location.href),
        'scope': 'QuanXianFanWei',
        'response_type': 'token'
    });

    //var uri = addQueryString(authorizeUrl, {
    //    'client_id': clientId,
    //    'redirect_uri': returnUrl + '?returnUrl=' + encodeURIComponent(window.location.href),
    //    'scope': 'QuanXianFanWei',
    //    'response_type': 'code',
    //});
    window.location.href = uri;
}


// 本地登录
function oauthBearerSignIn(token) {
    if (typeof (token) == 'undefined') { return; }
    $.cookie('oauth-bearer-token', token, { expires: bearer_expires, path: '/' })
    initOAuth();
    var returnObj = getReturnUrl();
    if (returnObj != undefined) {
        goToUrl(returnObj.returnUrl);
    } else {
        goToUrl("/");
    }

}

// 注销登录信息
function oauthBearerSignOut() {
    $.removeCookie('oauth-bearer-token', { path: '/' });
    goToUrl(oauthHost + signoutUrl + processReturnUrl(window.location.href));
}

// 检查是否登录
//loginEvent  已登录相应的事件
//notLoginEvent 未登录时相应的事件 
function isLogin(loginEvent, notLoginEvent) {
    $.post(apiHost + isOnLineUrl, {}, function (data) {
        if (isLogin) {
            if (typeof (loginEvent) != 'undefined') {
                loginEvent();
            }
        } else {
            if (typeof (notLoginEvent) != 'undefined') {
                notLoginEvent();
            }
        }
    });
}


//为请求初始化认证信息
function initOAuth() {
    var token = $.cookie('oauth-bearer-token');
    token = token ? token : '';

    $.ajaxSetup({
        beforeSend: function (xhr) {
            xhr.setRequestHeader('Authorization', 'Bearer ' + token);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            switch (XMLHttpRequest.status) {
                case 400:
                    ajaxError.NotFoundEvent(); break;
                case 401:
                    ajaxError.UnauthorizedEvent(); break;
                case 403:
                    ajaxError.ForbiddenEvent(); break;
                case 500:
                    ajaxError.ServerErrorEvent(); break;
                default:
                    ajaxError.OtherErrorEvent(); break;
            }
        }
    });

}

var ajaxError = {};

//未授权处理
ajaxError.UnauthorizedEvent = function () {
    goToSignIn();
}

//服务器错误处理
ajaxError.ServerErrorEvent = function () {

}

//403用于处理没有操作权限
ajaxError.ForbiddenEvent = function () {
    alert("抱歉，您没有对应的操作权限！");
}


//请求资源不存在错误处理
ajaxError.NotFoundEvent = function () {

}


//其他错误处理
ajaxError.OtherErrorEvent = function () {
    throw new Error("服务器发生错误！");
}



//为URL添加查询参数
function addQueryString(uri, parameters) {
    var delimiter = (uri.indexOf('?') == -1) ? '?' : '&';
    for (var parameterName in parameters) {
        var parameterValue = parameters[parameterName];
        uri += delimiter + encodeURIComponent(parameterName) + '=' + encodeURIComponent(parameterValue);
        delimiter = '&';
    }
    return uri;
}


//获取查询参数  转化为对象
function getSearchObj() {
    if (window.location.search.indexOf("?") === 0) {
        return parseQueryString(window.location.search.substr(1));
    } else {
        return undefined;
    }
}

//获取片段信息
function getFragment() {
    if (window.location.hash.indexOf("#") === 0) {
        return parseQueryString(window.location.hash.substr(1));
    } else {
        return undefined;
    }
}

//获取ReturnUrl参数
function getReturnUrl() {
    if (window.location.search.indexOf("?") === 0) {
        return parseQueryString(window.location.search.substr(1));
    } else {
        return undefined;
    }
}

//获取所有查询参数
function parseQueryString(queryString) {
    var data = {},
        pairs, pair, separatorIndex, escapedKey, escapedValue, key, value;

    if (queryString === null) {
        return data;
    }

    pairs = queryString.split("&");

    for (var i = 0; i < pairs.length; i++) {
        pair = pairs[i];
        separatorIndex = pair.indexOf("=");

        if (separatorIndex === -1) {
            escapedKey = pair;
            escapedValue = null;
        } else {
            escapedKey = pair.substr(0, separatorIndex);
            escapedValue = pair.substr(separatorIndex + 1);
        }

        key = decodeURIComponent(escapedKey);
        value = decodeURIComponent(escapedValue);

        data[key] = value;
    }

    return data;
}
